﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using System.IdentityModel.Tokens.Jwt;

namespace HECore.IdentityServer4.Interactive_App.MvcClient
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

            //将身份验证服务添加到 DI
            //我们使用 cookie 在本地登录用户（通过"Cookies"）DefaultScheme，
            //我们将设为DefaultChallengeScheme,
            //因为oidc当我们需要用户登录时，我们将使用 OpenID Connect 协议
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })
            //然后我们使用AddCookie添加可以处理 cookie 的处理程序
            .AddCookie("Cookies")
            .AddOpenIdConnect("oidc", options =>
            {
                options.Authority = "https://localhost:5001";

                options.ClientId = "mvc";
                options.ClientSecret = "secret";
                options.ResponseType = "code";

                options.SaveTokens = true;
                options.Scope.Add("profile");
                options.GetClaimsFromUserInfoEndpoint = true;
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute()
                    .RequireAuthorization();
                //RequireAuthorization 方法禁用整个应用程序的匿名访问
                //如果您想在每个控制器或操作方法的基础上指定授权，您也可以使用该属性 [Authorize]
            });
        }
    }
}
